package lk.icta.core.dao.impl;

import lk.icta.common.dao.impl.BaseDAO;
import lk.icta.core.dao.URMGOIUserDAO;
import lk.icta.core.entity.URMGOIUser;
import lk.icta.user.entity.User;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.Date;
import java.util.List;

/**
 * @author Tharanga Punchihewa
 */
public class URMGOIUserDAOImpl extends BaseDAO implements URMGOIUserDAO {


    @Transactional(propagation = Propagation.MANDATORY)
    public void addORMGOIUser(URMGOIUser urmgoiUser, User user) {
        logger.debug("Adding a UR-MGOI user ", urmgoiUser.getUserDetail().getName());
        urmgoiUser.getLifeCycleInfo().setCreatedUser(user);
        urmgoiUser.getLifeCycleInfo().setCreatedTimeStamp(new Date());
        urmgoiUser.getLifeCycleInfo().setLastUpdatedUser(user);
        urmgoiUser.getLifeCycleInfo().setLastUpdatedTimeStamp(new Date());
        em.persist(urmgoiUser);
    }

    @Transactional(propagation = Propagation.MANDATORY)
    public void updateORMGOIUser(URMGOIUser urmgoiUser, User user) {
        logger.debug("Update a UR-MGOI user :{}", urmgoiUser.getUserDetail().getName());
        URMGOIUser existing = getURMGOIByIdUKey(urmgoiUser.getId());
        urmgoiUser.getLifeCycleInfo().setCreatedTimeStamp(existing.getLifeCycleInfo().getCreatedTimeStamp());
        urmgoiUser.getLifeCycleInfo().setCreatedUser(existing.getLifeCycleInfo().getCreatedUser());
        urmgoiUser.getLifeCycleInfo().setLastUpdatedUser(user);
        urmgoiUser.getLifeCycleInfo().setLastUpdatedTimeStamp(new Date());
        em.merge(urmgoiUser);
    }

    @Transactional(propagation = Propagation.MANDATORY)
    public URMGOIUser getURMGOIByIdUKey(long id) {
        logger.debug("find a UR-MGOI user ,user id is :{}", id);
        return em.find(URMGOIUser.class, id);
    }

    @Transactional(propagation = Propagation.MANDATORY)
    public List<URMGOIUser> getURMGOIUserListByOrganization(int organizationId, User user) {
        logger.debug("Loading UR-mgoi user  list by organization id [Id: {}]", organizationId);
        Query q = em.createNamedQuery("getORMOIByOrganizationId");
        q.setParameter("organizationId", organizationId);
        return q.getResultList();
    }

    @Transactional(propagation = Propagation.MANDATORY)
    public URMGOIUser getURMGOIByUserName(String userName) {
        logger.debug("find a UR-MGOI user ,user Name is :{}", userName);
        Query q = em.createNamedQuery("getORMOIByUserName");
        q.setParameter("username", userName);
        return (URMGOIUser) q.getSingleResult();
    }

}